package com.tac.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.tac.common.Exception.TokenException;
import com.tac.common.result.Result;
import com.tac.common.thread.Thread;
import com.tac.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Configuration
@CrossOrigin
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        String uri = request.getRequestURI();
        log.info("拦截到请求：{}",uri);
        if (method.equalsIgnoreCase("options")) {
            return true;
        }

        String token = request.getHeader("token");
        //如果是查看商品详情 添加足迹这个功能就要随着有没有登录来判断 /product/selectById
        if(request.getRequestURI().equals("/product/selectById")){
           if(token==null){
               return true;
           }else {
               ValueOperations valueOperations = redisTemplate.opsForValue();
               String user = (String) valueOperations.get(token);
               User parseObject = JSON.parseObject(user, User.class);
               Thread.set(parseObject);
               return true;
           }
        }

        if(token==null){
            log.info("没有token请先登录",uri);
            throw new TokenException("请先登录");
        }
        Boolean aBoolean = redisTemplate.hasKey(token);

        if (aBoolean) {
            ValueOperations valueOperations = redisTemplate.opsForValue();
            String user = (String) valueOperations.get(token);
            log.info("拦截到地址{}---token验证成功",uri);
            //验证成功 存入线程
            User parseObject = JSON.parseObject(user, User.class);
            Thread.set(parseObject);
            return true;
        } else {
            log.info("拦截到地址{}---token有误",uri);
            throw new TokenException("token有误");
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Thread.remove();
    }
}
